// utils/device-manager.js
const mqttClient = require('./mqtt-client.js')
const onenetConfig = require('./onenet-config.js')

class DeviceManager {
  constructor() {
    this.devices = new Map()
    this.initMQTTListeners()
  }

  // 初始化 MQTT 监听
  initMQTTListeners() {
    const { productId, deviceName } = onenetConfig.product
    
    // 监听设备命令
    const commandTopic = onenetConfig.topics.deviceCommand
      .replace('{productId}', productId)
      .replace('{deviceName}', deviceName)

    mqttClient.onMessage(commandTopic, (payload, topic) => {
      this.handleDeviceCommand(payload)
    })

    // 监听属性获取请求
    const propertyTopic = onenetConfig.topics.propertyGet
      .replace('{productId}', productId)
      .replace('{deviceName}', deviceName)

    mqttClient.onMessage(propertyTopic, (payload, topic) => {
      this.handlePropertyGet(payload)
    })

    // 监听连接状态变化
    mqttClient.onConnectionChange((connected, error) => {
      this.onConnectionStateChange(connected, error)
    })
  }

  // 处理设备命令
  handleDeviceCommand(payload) {
    console.log('收到设备命令:', payload)
    
    try {
      const { id, method, params } = payload
      
      switch (method) {
        case 'control':
          this.executeDeviceControl(params)
          break
        case 'set_property':
          this.setDeviceProperties(params)
          break
        case 'get_property':
          this.reportDeviceProperties()
          break
        default:
          console.warn('未知的命令方法:', method)
      }
    } catch (error) {
      console.error('处理设备命令失败:', error)
    }
  }

  // 执行设备控制
  executeDeviceControl(params) {
    Object.keys(params).forEach(deviceId => {
      const commands = params[deviceId]
      this.controlDevice(deviceId, commands)
    })
  }

  // 控制具体设备
  controlDevice(deviceId, commands) {
    const device = this.devices.get(deviceId)
    if (!device) {
      console.warn(`设备 ${deviceId} 不存在`)
      return
    }

    console.log(`控制设备 ${deviceId}:`, commands)
    
    // 更新设备状态
    Object.keys(commands).forEach(key => {
      if (device.hasOwnProperty(key)) {
        device[key] = commands[key]
      }
    })

    // 触发设备状态变化事件
    this.emitDeviceStatusChange(deviceId, device)

    // 上报设备状态
    this.reportDeviceStatus(deviceId)
  }

  // 设置设备属性
  setDeviceProperties(properties) {
    Object.keys(properties).forEach(deviceId => {
      const props = properties[deviceId]
      const device = this.devices.get(deviceId)
      
      if (device) {
        Object.assign(device, props)
        this.emitDeviceStatusChange(deviceId, device)
      }
    })
  }

  // 处理属性获取请求
  handlePropertyGet(payload) {
    console.log('收到属性获取请求:', payload)
    this.reportDeviceProperties()
  }

  // 上报所有设备属性
  reportDeviceProperties() {
    const properties = {}
    
    this.devices.forEach((device, deviceId) => {
      properties[deviceId] = {
        name: device.name,
        type: device.type,
        status: device.status,
        powerState: device.powerState,
        online: device.online || true,
        lastUpdate: new Date().toISOString()
      }
    })

    mqttClient.reportDeviceProperty(properties)
  }

  // 上报单个设备状态
  reportDeviceStatus(deviceId) {
    const device = this.devices.get(deviceId)
    if (!device) return

    const data = {
      [deviceId]: {
        status: device.status,
        powerState: device.powerState,
        ...this.getDeviceSpecificData(device)
      }
    }

    mqttClient.reportDeviceData(data)
  }

  // 获取设备特定数据
  getDeviceSpecificData(device) {
    const data = {}
    
    switch (device.type) {
      case 'light':
        data.brightness = device.brightness
        data.color = device.color
        data.mode = device.mode
        break
      case 'ac':
        data.temperature = device.temperature
        data.mode = device.mode
        data.windSpeed = device.windSpeed
        break
      case 'tv':
        data.channel = device.channel
        data.volume = device.volume
        data.source = device.source
        break
    }
    
    return data
  }

  // 添加设备
  addDevice(device) {
    this.devices.set(device.id, device)
    console.log(`设备 ${device.id} 已添加`)
    
    // 上报设备添加事件
    this.reportDeviceData(device.id, 'device_added', device)
  }

  // 移除设备
  removeDevice(deviceId) {
    this.devices.delete(deviceId)
    console.log(`设备 ${deviceId} 已移除`)
    
    // 上报设备移除事件
    this.reportDeviceData(deviceId, 'device_removed', { deviceId })
  }

  // 上报设备数据
  reportDeviceData(deviceId, event, data) {
    const payload = {
      [deviceId]: {
        event: event,
        timestamp: Date.now(),
        data: data
      }
    }

    mqttClient.reportDeviceData(payload)
  }

  // 连接状态变化处理
  onConnectionStateChange(connected, error) {
    if (connected) {
      console.log('MQTT 连接已建立，开始上报设备状态')
      // 连接建立后上报所有设备状态
      this.reportDeviceProperties()
    } else {
      console.warn('MQTT 连接断开', error)
    }

    // 触发连接状态变化事件
    this.emitConnectionStateChange(connected, error)
  }

  // 事件发射器
  emitDeviceStatusChange(deviceId, status) {
    // 这里可以集成到小程序的全局事件系统
    if (typeof getApp === 'function') {
      const app = getApp()
      if (app && app.emitDeviceStatusChange) {
        app.emitDeviceStatusChange(deviceId, status)
      }
    }
  }

  emitConnectionStateChange(connected, error) {
    if (typeof getApp === 'function') {
      const app = getApp()
      if (app && app.emitConnectionStateChange) {
        app.emitConnectionStateChange(connected, error)
      }
    }
  }

  // 获取所有设备
  getAllDevices() {
    return Array.from(this.devices.values())
  }

  // 获取设备数量
  getDeviceCount() {
    return this.devices.size
  }
}

module.exports = new DeviceManager()